<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box,#box2{
              width: 100px;
              height: 100px;
              background: skyblue;
              position: absolute;
              left: 0;
              top : 0;
        }
        #box2{
              background: springgreen;
              left: 200px;
        }
  </style>
</head>

<body>
    <div id="box"></div>
    <div id="box2"></div>
</body>

</html>
<script>
    class Drag{
        constructor(selector){
            this.ele =document.querySelector(selector)
            this.bindEvent();
        }
        //tip：方法分割是没有逗号的；
        bindEvent(){
            let self =this;
            self.ele.onmousedown =function(evt){
                //拖拽开启
           // console.log("拖拽开启");
           let e = evt || event;
                              // 获取 offsetX 和 offsetY;
                              let { offsetX : x , offsetY : y } = e;
                              document.onmousemove = function(evt){
                                    let e = evt || event;
                                    // 拖拽进行中;
                                    // console.log("拖拽进行中");
                                    // 为了让元素跟着鼠标点击的位置走而不是跟着鼠标的client 走;
                                    self.eleMove( e.clientX - x , e.clientY - y);
                              }
                        }
                        this.ele.onmouseup = function( ){
                              // console.log("拖拽结束");
                              document.onmousemove = null;
                        }
                  }
                  eleMove( x , y ){
                        this.ele.style.left = x + "px";
                        this.ele.style.top  = y + "px";
                  }

            }

            var drag1 = new Drag("#box");
            var drag2 = new Drag("#box2");
</script>